/*
 * @Description: 编辑广告
 * @Author: kanglin
 * @Date: 2018-06-20 10:05:57
 * @Copyright: Created by Panxsoft.
 */

<style lang="less" scoped rel="stylesheet/less" type="text/less" >
    .advert-edit{

      .redirect_img_thumb {
        height: 50px;
        vertical-align: middle;
      }
		}
				  .v-component-bosupload {
        position: relative;
        display: inline-block;
        background: #fff;
        border: 1px solid #dddee1;
        border-radius: 4px;
        padding: 6px 23px;
        overflow: hidden;
        color: #495060;
        text-decoration: none;
        text-indent: 0;
		     line-height: 20px;
		     max-width: 288px;
		    white-space: nowrap;
		     text-overflow: ellipsis;
        input[type='file'] {
            position: absolute;
            font-size: 100px;
            right: 0;
            top: 0;
			      opacity: 0;
			     max-width: 300px;
        }
        &:hover {
            // background: #AADFFD;
            border-color: #57a3f3;
            color: #57a3f3;
            text-decoration: none;
        }
    }
</style>

<template>
	<div class="advert-edit">
		<Form
			ref="formValidate"
			:model="formValidate"
			:rules="ruleValidate"
			:label-width="labelWidth(120,140)"
			name="edit__form">

			<FormItem
				:label="$t('advert.name')"
				prop="name">
				<i-input
					v-model="formValidate.name"
					:placeholder="$t('advert.please_enter_name')"
					name="create__name"/>
			</FormItem>

			<Form-item
				:label="$t('advert.media_type')"
				prop="advert_type_id">

				<Select
					v-model="formValidate.advert_type_id"
					clearable
					filterable
					style="width:200px"
					name="create-advert"
				>
					<Option
						v-for="item in advert_types"
						:value="item.id"
						:key="'advert_type' + item.id">{{ item.name }}
					</Option>
				</Select>

			</Form-item>

			<!-- 多语言 -->
			<Tabs
				v-model="language_id"

			>
				<TabPane
					v-for="(locale_suggest, locale_idx) in language_index"
					:key="`hm_tab_lang[${locale_idx}]`"
					:label="locale_suggest.name"

				>

					<!-- 中文.视频图片-->
					<Form-item
						v-if="formValidate.advert_type_id"
						v-show="locale_idx==1?false:true"
						:label="$t('advert.advert_img_video')"
						prop="instruction_zh_img"
					>

						<a
							href="javascript:;"
							class="v-component-bosupload">
							{{ file_info || $t('bosupload.selector') }}
							<input
								ref="bos_btn"
								:accept="accept"
								:multiple="multiple"
								:name="name"
								:tips="$t('advert.select_file')"
								:file-type-reg-exp="fileTypeRegExp"
								type="file"

								@change="changeInput">

						</a>
						<p>{{ uploadTips }}</p>
					</Form-item>

					<!-- 英文视频图片-->
					<Form-item
						v-if="formValidate.advert_type_id"
						v-show="locale_idx==1?true:false"
						:label="$t('advert.advert_img_video')"
						prop="instruction_en_img"
					>

						<a
							href="javascript:;"
							class="v-component-bosupload">
							{{ file_info_en || $t('bosupload.selector') }}
							<input
								ref="bos_btn"
								:accept="accept"
								:multiple="multiple"
								:name="name"
								type="file"

								@change="changeInput_en">
						</a>
						<p>{{ uploadTips_en }}</p>
					</Form-item>


					<!-- 中文跳转类型 -->
					<Form-item
						v-show="locale_idx==1?false:true"
						:label="$t('advert.redirect_type')"
						prop="redirect_zh_type">

						<Select
							v-model="formValidate.redirectable_zh_type"
							:placeholder="$t('common.none')"
							clearable
							name="create__redirectable_zh_type"

						>
							<Option
								v-for="redirect_type in redirect_types"
								:value="redirect_type.id"
								:key="'redirect_type' + redirect_type.id">{{ redirect_type.name }}
							</Option>
						</Select>
					</Form-item>

					<!-- 中文跳转网址 -->
					<Form-item
						v-show="locale_idx==1?false:true"
						:label="$t('advert.redirect_url')"
						required
						prop="redirect_zh_url">

						<i-input
							v-model="formValidate.redirect_zh_url"
							:placeholder="$t('advert.please_enter_url')"
							name="create__redirect_zh_url"/>
					</Form-item>

					<!-- 英文跳转类型 -->
					<Form-item
						v-show="locale_idx==1?true:false"
						:label="$t('advert.redirect_type')"
						prop="redirect_en_type">

						<Select
							v-model="formValidate.redirectable_en_type"
							:placeholder="$t('common.none')"
							clearable
							name="create__redirectable_en_type"

						>
							<Option
								v-for="redirect_type in redirect_types"
								:value="redirect_type.id"
								:key="'redirect_type' + redirect_type.id">{{ redirect_type.name }}
							</Option>
						</Select>
					</Form-item>

					<!-- 英文跳转网址 -->
					<Form-item
						v-show="locale_idx==1?true:false"
						:label="$t('advert.redirect_url')"
						required
						prop="redirect_en_url">

						<i-input
							v-model="formValidate.redirect_en_url"
							:placeholder="$t('advert.please_enter_url')"
							name="create__redirect_en_url"/>
					</Form-item>
				</TabPane>
			</tabs>


			<Form-item

				:label="$t('advert.play_second')"
				prop="play_second">
				<InputNumber
					:max="60*60*12"
					:min="1"
					v-model="formValidate.play_second"
					:placeholder="$t('advert.please_enter_play_second')"
					name="create__play_second"/>
			</Form-item>

			<!-- 是否跳过广告 -->
			<Form-item
				:label="$t('advert.ispass_advert')"
			>
				<RadioGroup
					v-model="formValidate.radio"

				>
					<Radio label="true">是</Radio>
					<Radio label="false">否</Radio>
				</RadioGroup>

			</Form-item>

			<!-- 排序 -->
			<Form-item
				:label="$t('announcement.sort_order')"
				prop="sort_order">
				<InputNumber
					:min="1"

					v-model="formValidate.sort_order"
					:placeholder="$t('announcement.please_select_sort_order')"
					name="create-sort"/>
			</Form-item>


			<!-- 开始时间 -->

			<Form-item
				:label="$t('announcement.started_at')"
				prop="started_at">
				<DatePicker
					v-model="formValidate.started_at"
					:style="{width: '260px'}"
					:placeholder="$t('announcement.please_select_started_at')"
					type="datetime"
					placement="top"
					name="create-started_at"
					@on-change="changeSTDate"/>
			</Form-item>

			<!-- 结束时间 -->
			<Form-item
				:label="$t('announcement.ended_at')"
				prop="ended_at">
				<DatePicker
					v-model="formValidate.ended_at"
					:style="{width: '260px'}"
					:placeholder="$t('announcement.please_select_ended_at')"
					type="datetime"
					placement="top"
					name="create-ended_at"
					@on-change="changeEDDate"/>
			</Form-item>

			<!-- 提交 -->
			<Form-item>
				<Button
					type="primary"
					name="edit__submit"
					@click="handleSubmit('formValidate')">{{ $t('common.update') }}</Button>
			</Form-item>
		</Form>
	</div>
</template>

<script>
// import bosUpload from 'src/views/component/bosupload';
import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import Uploader from 'src/views/component/Uploader';
import { $t } from 'src/i18n';
import { mapMutations } from 'vuex';
import { isUrlValidate } from 'src/utils/utils';

const [ADVERT_TYPE_ID_IMAGE, ADVERT_TYPE_ID_VIDEO, ADVERT_TYPE_ID_TABLE_PLAQUE] = [1, 2, 3]; // 常量
const [REDIRECTABLE_TYPE_URL] = ['Url'];

export default {
	name: 'AdvertEdit',
	components: {
		Uploader,
	},
	mixins: [labelWidthMixin],
	props: {
		// bosConfig: {
		// 	type: Object,
		// 	required: true,
		// },
		// storeDevices: {
		// 	type: Array,
		// 	required: true,
		// },
		// update: {
		// 	type: Function,
		// 	required: true,
		// },
		advert_types: {
			type: Array,
			default() {
				return [];
			},
		},
		language_index: {
			type: Array,
			default() {
				return [];
			},
		},
		manufacturer_solo: {
			type: Object,
			default() {
				return {};
			},
		},
		multiple: {
			type: Boolean,
			default() {
				return false;
			},
		},
		name: {
			type: String,
			default() {
				return '';
			},
		},

	},
	data() {
		return {
			file_info: '',

			file_info_en: '',
      	is_show: 1, // 1表示跳过
      	 real_started_at: '', // 格式化后的开始时间
        	language_id: 0,
			 real_ended_at: '', // 格式化后的结束时间

			formValidate: {
				advert_type_id: '', // 广告类别id 1 图片 2 视频
				name: null, // 广告名称
				// content_key: null, // 广告内容 bos的key值 ，create方法获取bos 配置
				play_second: 15, // 播放时长
				// device_account_ids: [], // 设备id，create 方法获取

				// redirectable_id: 0, // 跳转ID
      	redirectable_zh_type: '', // 跳转类型
				redirectable_en_type: '', // 跳转类型
			  sort_order: 1, // 排序

				redirect_zh_url: '', // 跳转网址的地址
				redirect_en_url: '', // 跳转网址的地址

				started_at: '', // 开始时间

				ended_at: '', // 结束时间

				radio: 'true',

				instruction_zh_img: '',

				instruction_en_img: '',
			}, // 更新表单数据

			/**
       * 表单验证规则
       * @see {@link https://github.com/yiminghe/async-validator}
       */
			ruleValidate: {
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('advert.name') }),
						trigger: 'blur',
					},
				],
				play_second: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('advert.play_second') }),
						trigger: 'blur',
					},
				],
        	sort_order: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('announcement.sort_order') }),
						trigger: 'blur,change',
					},
				],
				started_at: [
					{
						required: true,
						type: 'date',
						message: this.$t('validate.required', { field: this.$t('announcement.started_at') }),
						trigger: 'blur,change',
					},
				],
				ended_at: [
					{
						required: true,
						type: 'date',
						message: this.$t('validate.required', { field: this.$t('announcement.ended_at') }),
						trigger: 'blur,change',
					},
				],
				advert_type_id: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('advert.media_type') }),
						trigger: 'blur,change',
					},
				],
				redirect_url: [{
					trigger: 'blur,change',
					validator: this.validateRedirectUrl.bind(this),
				}],
				redirect_zh_url: [{
					trigger: 'blur,change',
					validator: this.validateRedirectUrl.bind(this),
				}],
				redirect_en_url: [{
					trigger: 'blur,change',
					validator: this.validateRedirectUrl.bind(this),
				}],
			},
			// },
			image: ADVERT_TYPE_ID_IMAGE, // 指定当前选项的value值
			video: ADVERT_TYPE_ID_VIDEO, // 指定当前选项的value值
			accepts: { // 设置 bos accept
				[ADVERT_TYPE_ID_IMAGE]: 'image/gif, image/jpeg, image/png',
				[ADVERT_TYPE_ID_VIDEO]: 'video/mp4',
			},
			   [ADVERT_TYPE_ID_TABLE_PLAQUE]: 'image/gif, image/jpeg, image/png',

			regExps: { // 设置 校验文件类型的正则
				[ADVERT_TYPE_ID_IMAGE]: /(image\/gif|image\/jpeg|image\/png)/i,
				[ADVERT_TYPE_ID_VIDEO]: /video\/MP4/i,
				[ADVERT_TYPE_ID_TABLE_PLAQUE]: /(image\/gif|image\/jpeg|image\/png)/i,
			},
			tips: { // 提示
				[ADVERT_TYPE_ID_VIDEO]: this.$t('advert.video_format'),
				[ADVERT_TYPE_ID_IMAGE]: this.$t('advert.image_format'),
				[ADVERT_TYPE_ID_TABLE_PLAQUE]: this.$t('advert.image_format'),
			},

			TYPE_IMAGE: ADVERT_TYPE_ID_IMAGE,
			TYPE_VIDEO: ADVERT_TYPE_ID_VIDEO,
			TYPE_TABLE_PLAQUE: ADVERT_TYPE_ID_TABLE_PLAQUE,
			REDIRECTABLE_TYPE_URL,

			redirect_types: [
				{ name: this.$t('advert.redirect_url'), id: REDIRECTABLE_TYPE_URL },
			],
		};
	},
	computed: {
		accept() {
			const key = this.formValidate.advert_type_id;
			return this.accepts[key];
		},
		fileTypeRegExp() {
			const key = this.formValidate.advert_type_id;
			return this.regExps[key];
		},
		uploadTips() {
			const key = this.formValidate.advert_type_id;
			return this.tips[key];
		},
		uploadTips_en() {
			const key = this.formValidate.advert_type_id;
			return this.tips[key];
		},
	},

	watch: {
		// 'formValidate.advert_type_id': {
		// 	handler() {
		// this.removeFile();
		// this.file_name = ''; // 文件名
		// 	},
		// },
	},


	created() {
		       if (this.manufacturer_solo) {
						 console.log(this.manufacturer_solo);
			this.formValidate.advert_type_id = this.manufacturer_solo.advert_type_id;

			this.formValidate.name = this.manufacturer_solo.name;

			this.formValidate.play_second = this.manufacturer_solo.play_second;

			this.file_info = this.parseFileName(this.manufacturer_solo.advert_descriptions[0].content);

			this.file_info_en = this.parseFileName(this.manufacturer_solo.advert_descriptions[1].content);

			this.formValidate.sort_order = this.manufacturer_solo.sort_order;

			this.real_started_at = this.manufacturer_solo.started_at;

			this.real_ended_at = this.manufacturer_solo.ended_at;

			this.formValidate.started_at = this.manufacturer_solo.started_at;

			this.formValidate.ended_at = this.manufacturer_solo.ended_at;

			this.formValidate.can_skip = this.manufacturer_solo.can_skip;

			this.formValidate.instruction_zh_img = this.manufacturer_solo.advert_descriptions[0].content;

			this.formValidate.instruction_en_img = this.manufacturer_solo.advert_descriptions[1].content;

			this.formValidate.redirectable_zh_type = this.manufacturer_solo.advert_descriptions[0].redirectable_type;

			this.formValidate.redirectable_en_type = this.manufacturer_solo.advert_descriptions[1].redirectable_type;

			if (this.manufacturer_solo.advert_descriptions[0].redirectable !== null) {
				 this.formValidate.redirect_zh_url = this.manufacturer_solo.advert_descriptions[0].redirectable.url;

				this.formValidate.redirect_en_url = this.manufacturer_solo.advert_descriptions[1].redirectable.url;
					 }
		}
	},

	methods: {
		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),
			    parseFileName(url) {
			if (url) {
				return url.replace(/^.+\//, ''); // 将文件名和拓展名的部分替换为''
			}
			return null;
		},
		// 切换英文tabs
		change_en_language() {
			if (event.keyCode == 9) {
							 this.language_id = 1;
				 }
		},
		// 切换中文tabs
		change_zh_language() {
      	if (event.keyCode == 9) {
							 this.language_id = 0;
				 }
		},

		changeSTDate(date) {
			this.real_started_at = date;
		},

		changeEDDate(date) {
			this.real_ended_at = date;
		},

		/**
     * 文件名替换
     * @param  {String} url {文件路径}
     * @return {undefined}
     */
		// parseFileName(url) {
		// 	if (url) {
		// 		return url.replace(/^.+\//, ''); // 将文件名和拓展名的部分替换为''
		// 	}
		// 	return null;
		// },

		/**
     *  执行更新
     * @param {Object} form {表单数据}
     * @return {undefined}


		/**
     * 更新表单
     * @return {undefined}
     */
		handleSubmit(name) {
			this.$refs[name].validate((valid) => {
				if (valid) {
					if (this.formValidate.instruction_zh_img == '') {
						this.$Message.error(this.$t('advert.file_cannot_be_empty_zh'));
						return;
					}
					if (this.formValidate.instruction_en_img == '') {
						this.$Message.error(this.$t('advert.file_cannot_be_empty_en'));
						return;
					}
					 this.$emit('update', this.manufacturer_solo.id, this.formDataCreate());
					 			} else {
					this.$Message.error(this.$t('common.invalid_form_data'));
				}
			});
		},

		 /**
         * 手动拼接表单数据
		 * @param {new_object} {拼接表单对象}
         * @return {undefined}
         */
		formDataCreate() {
			if (this.formValidate.radio == 'false') {
			   this.is_show = 0;
			 }


			const new_array = [
				{
					id: 1,
					content: this.formValidate.instruction_zh_img,
				},
				{
					id: 3,
					content: this.formValidate.instruction_en_img,
				},
			];


			 if (this.formValidate.redirectable_zh_type && this.formValidate.redirectable_en_type) {
				 new_array[0].redirectable_type = this.formValidate.redirectable_zh_type;
				 new_array[1].redirectable_type = this.formValidate.redirectable_en_type;

				  new_array[0].redirect_url = this.formValidate.redirect_zh_url;
				 new_array[1].redirect_url = this.formValidate.redirect_en_url;
			 }

			const new_object = {
				_method: 'PUT',

				name: this.formValidate.name,

				advert_type_id: this.formValidate.advert_type_id,

				sort_order: this.formValidate.sort_order,

				started_at: this.real_started_at,

				ended_at: this.real_ended_at,

				can_skip: this.is_show,
			};

			if (this.formValidate.advert_type_id !== 2) {
				   new_object.play_second = this.formValidate.play_second;
			}

			const form_data = new FormData();

			Object.keys(new_object).forEach((key) => {
				form_data.append(key, new_object[key]);
			});

     			// dexcriptions需为数组
			for (let i = 0; i < new_array.length; i++) {
				for (const key in new_array[i]) {
					form_data.append(`descriptions[${new_array[i].id}][${key}]`, new_array[i][key]);
				}
			}


			return form_data;
		},


		changeInput(e) {
			console.log(e);
			this.formValidate.instruction_zh_img = e.target.files[0];
			if (this.validateFileType(e.target.files[0])) {
				this.file_info = e.target.files[0].name;
			} else {
				this.file_info = '';
			}
		},

		changeInput_en(e) {
			this.formValidate.instruction_en_img = e.target.files[0];
			if (this.validateFileType(e.target.files[0])) {
				this.file_info_en = e.target.files[0].name;
			} else {
				this.file_info_en = '';
			}
		},

		validateRedirectId(rule, value, callback) {
			if (this.formValidate.redirectable_type && !value) {
				callback(this.$t('validate.required', { field: this.$t('common.option') }));
			} else {
				callback();
			}
		},

		validateRedirectUrl(rule, value, callback) {
			const isRedirectTypeUrl = this.formValidate.redirectable_type === this.REDIRECTABLE_TYPE_URL;

			if (isRedirectTypeUrl && !isUrlValidate(value)) {
				callback(this.$t('validate.url', { field: this.$t('advert.redirect_url') }));
			} else {
				callback();
			}
		},
		validateFileType(file) {
			if (!file) {
				this.$Message.error(this.$t('bosupload.no_files_selected')); // 未选择任何文件！
				return;
			}

			const file_type = file.type;

			if (this.fileTypeRegExp.test(file_type)) {
				if (parseFloat(file.size) / 1024 > 102400) {
					this.$Message.error(this.$t('bosupload.size_max', { value: '100m' })); // '所选文件超过100M限制！'

					this.$emit('validate', false);

					return false;
				}

				this.$emit('validate', true);

				return true;
			}

			this.$Message.error(this.$t('bosupload.format_error')); // 所选文件格式不正确！

			this.$emit('validate', false);

			return false;
		},

	},
};
</script>
